<template>
  <ElCard class="blog-conments--write box-card">
    <h3>评论区</h3>
    <textarea ref="conTextarea" v-model="content" class="blog-conments--input" placeholder="请输入评论内容" />
    <ElButton class="blog-conments--submit" type="primary" plain @click="subConment">提交</ElButton>
  </ElCard>
</template>

<script setup lang="ts">
import { ElNotification } from 'element-plus'
import { inject, ref, onMounted, withDefaults } from 'vue'

import $http from '@/api/http'
import { $bus } from '@/unit/mitt'
let props = withDefaults(
  defineProps<{
    aid: string
  }>(),
  { aid: '' },
)
let getArticleById = inject<Function>('getArticleById')
let content = ref<string>('')
let conTextarea = ref<null | HTMLTextAreaElement>(null)
onMounted(() => {
  // TODO, 后续操作
  $bus.on('focusTextarea', () => {
    focusTextarea()
  })
})

// 如果没有填写内容, 发出警告提示, 并且自动聚焦到textArea
function focusTextarea() {
  conTextarea.value?.focus()
}
async function subConment() {
  if (!content.value.trim()) {
    ElNotification({
      title: '警告',
      message: '请填写内容',
      type: 'warning',
    })
    focusTextarea()
    return false
  }
  try {
    $http({
      type: 'postConments',
      data: { aid: props.aid, content: content.value },
    })
    getArticleById()
    ElNotification({
      title: '提交成功',
      type: 'success',
    })
    content.value = ''
  } catch (err) {
    console.log(err)
    ElNotification({
      title: '文章获取失败',
      message: err.message,
      type: 'error',
    })
  }
}
</script>
<style lang="stylus">
.blog-conments--write
  margin-top 16px
  & h3
    padding 8px
</style>
